<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :title="'结算送审'"
    :visible.sync="visible"
    custom-class="ledger"
    fullscreen top="5vh"
    width="1200px"
    :before-close="cancelDialog">
    <div class="colums">
      <div class="colums_left">
        <div class="colums_left_middle">
          <div class="middleForm ledger">
            <el-form ref="dataForm" :model="form" class="el-dialog__body" label-width="100px">
              <div class="title">项目信息</div>
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="100px" label="项目名称" prop="projectName" :rules="{required: true, message: '项目名称不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.projectName" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="100px" label="编制人:">
                    {{form.projectManage}}
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">基本信息</div>
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="合同金额 (元)" prop="contractAmount" :rules="rules.contractAmount" >
                    <el-input-number v-model="form.contractAmount" :min="0" v-thousand style="width: 200px"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="送审金额 (元)" prop="submittalAmount" :rules="{ required: true, type:'number',  message: '送审金额不能为空', trigger: ['blur', 'change']}">
                    <el-input-number v-model="form.submittalAmount" v-thousand :min="0" style="width: 200px"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="竣工验收日期">
                    <el-date-picker placement="bottom-start" clearable v-model="form.acceptanceDate" type="date"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="建设单位" prop="developerName" :rules="{required: true, message: '建设单位不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.developerName" @focus="showTransferDialog(['developerId','developerName'], 'developer', false, [1 , 2])" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="联系人" prop="developerContactsName" :rules="{required: true, message: '建设单位联系人不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.developerContactsName" @focus="showTransferDialog(['developerContactsId','developerContactsName'], 'auditedUser', false, )" :readonly="true"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="电话">
                    <el-input v-model="form.developerPhone"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="施工单位" prop="constructionUnitName" :rules="{required: true, message: '施工单位不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.constructionUnitName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="110px" label="联系人" prop="constructionUnitContactsName" :rules="{required: true, message: '施工单位联系人不能为空', trigger: ['blur', 'change']}">
                    <el-input v-model="form.constructionUnitContactsName"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="100px" label="电话">
                    <el-input v-model="form.constructionUnitPhone"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="title">竣工结算审计送审资料清单</div>
              <el-row>
                <el-col :span="12">
                  <el-button icon="el-icon-plus" size="small" type="primary" @click="onAddItem">新建</el-button>
                  <el-button icon="el-icon-document-copy" @click="addSelectedRow">复制</el-button>
                  <el-button icon="el-icon-delete" @click="deleteSelectedRows">删除</el-button>
                  <el-button icon="el-icon-delete-solid" @click="clearTableData" >删除全部</el-button>
                </el-col>
                <el-col :span="8" :push="4" style="margin-top: 5px;">
                  <b style="color: #F56C6C">注意：</b><b style="color: #9E9E9E">务必填写资料份数，否则送审时将被剔除。</b>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-table
                    ref="table"
                    :data="tableData"
                    :model="tableData"
                    v-loading="loading"
                    style="width: 100%"
                    max-height="450"
                    highlight-current-row
                    @selection-change="updateSelectedRows"
                    @current-change="handleCurrentChange"
                  >
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column label="序号" width="50">
                      <template #default="{ $index }">
                        <span>{{ $index + 1 }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="纸质文件" width="180" align="center">
                      <template #default="{ row }">
                        <el-radio-group v-model="row.paperBased">
                          <el-radio border style="margin: 0 5px 0 5px" :label="1">是</el-radio>
                          <el-radio border style="margin: 0 5px 0 5px" :label="0">否</el-radio>
                        </el-radio-group>
                      </template>
                    </el-table-column>
                    <el-table-column label="资料名称">
                      <template #default="{ row }">
                        <el-row>
                          <el-col :span="1">
                            <span v-if="row.required === 1" style="color: #F56C6C">*</span>
                          </el-col>
                          <el-col :span="23" v-if="row.isView">
                            <span :class="{ 'view-with-margin': row.required === 0 }">{{ row.name }}</span>
                          </el-col>
                          <el-col :span="23" v-if="!row.isView">
                            <el-input v-model="row.name" :autosize="{ minRows: 1}" type="textarea" placeholder="输入资料名称"
                                      :class="{ 'input-with-margin': row.required === 0 }">
                            </el-input>
                          </el-col>
                        </el-row>
                      </template>
                    </el-table-column>
                    <el-table-column label="上传资料" width="140">
                      <template #default="{ row, $index }">
                        <el-upload v-if="row.paperBased === 0"
                                   class="upload-demo"
                                   ref="upload"
                                   action="/admin/sys-file/upload"
                                   :headers="{Authorization}"
                                   :on-success="(e) => handleSuccess(e, $index)"
                                   :on-preview="handlePreview"
                                   :on-remove="(file, fileList) => handleRemove(file, fileList, $index)"
                                   :show-file-list="true"
                                   :file-list="row.fileList">
                          <i class="el-icon-paperclip" style="color: #409EFF;"></i>
                        </el-upload>
                      </template>
                    </el-table-column>
                    <el-table-column label="份数" align="center">
                      <template slot="header" slot-scope="scope">
                        <el-button icon="el-icon-minus" size="mini" circle style="border-radius: 3px;" @click="changeCopies(-1)"></el-button>
                        <div style="width: 28px; display: inline-block; margin: 0 23px;">份数</div>
                        <el-button icon="el-icon-plus" size="mini" circle style="border-radius: 3px;" @click="changeCopies(1)"></el-button>
                      </template>
                      <template #default="{ row }">
                        <el-input-number v-model="row.copies" type="number" size="mini" :min="0" ></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column label="备注">
                      <template #default="{ row }">
                        <el-input v-model="row.remark" :autosize="{ minRows: 1}" type="textarea" placeholder="输入备注"></el-input>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button icon="el-icon-close" size="small" @click="cancelDialog">关闭</el-button>
              <el-button icon="el-icon-check" size="small" type="primary" @click="submit">保存</el-button>
              <el-button type="primary" size="small" icon="el-icon-check" @click="submitAudit">保存送审</el-button>
            </span>
          </div>
        </div>
      </div>
    </div>
    <FormTransfer :transferDialog="transferDialog" :transferDialogType="transferDialogType" :multiple="transferDialogMultiple" :transferCurrent="transferCurrent" @transferData="transferDataHandle" @closeTransfer="closeTransfer"/>

  </el-dialog>

</template>

<script>
import {mapGetters} from "vuex";
import FormTransfer from "@/components/form/transfer";
import WebDocument from '@/components/form/webDocument.vue';
import {getNoticeByProjectId, submit, submitAudit, getFileList} from "@/api/adis/project/notice";
import Template from "@/views/adis/base/template.vue";

export default {
  name: 'engineeringNoticeForm',
  props: {
    id: {
      type: String,
      default: ''
    },
    projectId: {
      type: String,
      default: ''
    },
  },
  mounted() { // 检测prop中id的值
    if (this.id) { // 如果不为空，开始初始化页面
      this.init({ projectId: this.id });
    } else if (this.projectId){
      this.init({ projectId: this.projectId });
    }
  },
  components: {
    Template,
    FormTransfer,
    WebDocument
  },
  data() {
    return {
      visible: false,
      loading: false,
      projectDisplay: false,
      multiple: false,
      transferDialog: false,
      transferDialogType: '',
      transferDialogTypeArr: [],
      transferDialogMultiple: false,
      transferCurrent: {},
      projectDialog: false,

      // 临时保存旧表单数据
      templateForm: [],
      form: {
        contractAmount: 0,
      },

      rules: {
        contractAmount:[
          { required: true, message: '该字段不能为空', trigger: 'blur' },
          { type:'number', min: 100000, message: '金额低于100000，属于自行审核项目', trigger: ['blur', 'change'] }
        ],
      },


      // 通知书组件
      auditView: '',

      tableData: [], // 资料清单数据
      selectedRows: [], // 存储选中的行数据
      selectedRow: {},
      Authorization: '',
    }
  },
  computed: {
    ...mapGetters(["permissions", 'userInfo']),
  },
  watch: {
    // 检测资料清单，如果被全数删除，立即补充一条空的清单
    tableData(newVal){
      if ((!newVal || newVal.length <= 1) && this.tableData.length <= 0){
        this.onAddItem(this.tableData)
      }
    },
  },
  created() {
    this.Authorization = 'Bearer ' + this.$store.getters.access_token
  },
  methods: {
    // -- 页面初始化
    init(params, type) {
      if (params && !type ) this.projectDisplay = true
      this.$nextTick(() => {
        if (params.projectId) {
          getNoticeByProjectId(params.projectId).then((noticeResponse) => {
            this.$set(this, "form", noticeResponse.data.data);
            this.$set(this.form, "developerId", this.form.developerId ? this.form.developerId : params.deptId)
            this.$set(this.form, "developerName", this.form.developerName ? this.form.developerName : params.deptName)
            this.form.projectYear = this.form.projectYear + '';
            this.visible = true;

            // 打开页面后再加载tableData,避免出现文本框渲染错误的情况
            if (this.form.noticeAttachments && this.form.noticeAttachments.length > 0){
              this.loading = true
              setTimeout(() => {
                this.tableData = this.form.noticeAttachments || []
                this.tableData.forEach(item => {
                  item.fileList = []
                  item.attachments.forEach(col => {
                    item.fileList.push({name: col.fileName, url: col.fileUrl})
                  })
                })
                this.loading = false
              }, 500)
            }
          })
        } else {
          getFileList(4).then((res)=>{
            this.$set(this, "form", {})
            this.$set(this.form, "projectManage", params.projectManage)
            this.$set(this.form, "projectDate", new Date().toISOString())
            this.$set(this.form, "developerId", params.deptId)
            this.$set(this.form, "developerName", params.deptName)
            this.visible = true;

            if (res.data.data && res.data.data.length > 0){
              this.loading = true
              setTimeout(() => {
                this.tableData = res.data.data || []
                this.tableData.forEach(item => {
                  item.paperBased = 0;
                  item.isView = true;
                })
                this.loading = false
              }, 500)
            }
          })
        }
      })
    },

    // -- 资料上传
    handleRemove(file, fileList, i) {
      this.tableData[i].fileList.forEach((item, v) => {
        if (file.url === item.url) this.tableData[i].fileList.splice(v, 1)
      })
    },
    handlePreview(file) {
      window.open(file.url ? file.url : file.response.data.url)
    },
    handleSuccess(e, v) {
      if (!this.tableData[v].fileList) {
        this.tableData[v].fileList = [{url: e.data.url, name: e.data.fileName}]
      } else {
        this.tableData[v].fileList.push({url: e.data.url, name: e.data.fileName})
      }
    },

    // -- 资料清单
    changeCopies(val){
      this.tableData.forEach(selectedRow => {
        selectedRow.copies += val
      })
    },

    addSelectedRow() {
      if (this.selectedRows.length > 0) {
        this.selectedRows.forEach(selectedRow => {
          const index = this.tableData.indexOf(selectedRow);
          if (index !== -1) {
            this.onAddItem(selectedRow)
          }
        });
      } else if (Object.keys(this.selectedRow).length !== 0){
        this.onAddItem(this.selectedRow)
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    clearTableData() {
      this.tableData = this.tableData.filter(item => item.required !== 0);
    },
    onAddItem(val) {
      // 在这里添加添加新项目的逻辑
      if (!this.tableData) this.tableData = []
      this.tableData.push({
        copies: val.copies || 0,
        required: val.required || 0,
        paperBased: val.paperBased || 0,
        name: val.name || '',
        remark: val.remark || '',
      })
    },
    deleteSelectedRows() {
      if (this.selectedRows.length > 0) {
        let warningShown = false;
        this.selectedRows.forEach((selectedRow) => {
          if (selectedRow.required === 0) {
            const index = this.tableData.indexOf(selectedRow);
            if (index !== -1) {
              this.tableData.splice(index, 1);
            }
          } else {
            if (!warningShown) {
              this.$message({
                type: "warning",
                message: "选中的必传资料不能被删除"
              });
              warningShown = true;
            }
          }
        });
       } else if (Object.keys(this.selectedRow).length !== 0){
        const index = this.tableData.indexOf(this.selectedRow);
        if (this.selectedRow.required === 0) {
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        } else {
          this.$message({
            type: "warning",
            message: "第" + index + 1 + "行为必传资料不能被删除"
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请选择一条数据!"
        });
      }
    },
    updateSelectedRows(selection) {
      this.selectedRows = selection;
    },
    handleCurrentChange(selection){
      this.selectedRow = selection;
    },

    // 表单提交
    submit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(item.name === ''){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行资料名称不能为空"
                });
                count++
                throw Error();
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return
          this.form.noticeAttachments = []
          this.tableData.forEach((item, i) => {
            item.attachments = []
            if (item.fileList){
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
            }
            this.form.noticeAttachments.push(item)
          })
          if(this.form.tenureDates){
            this.form.tenureStartDate = this.form.tenureDates[0]
            this.form.tenureEndDate = this.form.tenureDates[1]
          }

          this.form.auditType = 4
          this.loading = true;
          submit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },

    submitAudit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.fileList && this.fileList.map((file) => {
            this.form.fileUrl = file.response ? file.response.data.url : file.url
          });
          let count = 0
          try{
            this.tableData.forEach((item, i) => {
              if(item.name === ''){
                this.$message({
                  type: "warning",
                  message: '第' + (i + 1) + "行资料名称不能为空"
                });
                count++
                throw Error();
              }
              if(item.required !== 0 ){
                if (item.paperBased !== 1 && item.fileList.length === 0){
                  this.$message({
                    type: "warning",
                    message: '第' + (i + 1) + "行资料附件未上传"
                  });
                  count++
                  throw Error();
                }
              }
            })
          }catch(e){
            console.log(e)
          }
          if (count > 0) return
          this.form.noticeAttachments = []
          this.tableData.forEach((item, i) => {
            item.attachments = []
            if (item.fileList && item.copies !== 0){
              item.fileList.forEach(file => {
                item.attachments.push({fileName: file.name, fileUrl: file.url})
              })
              this.form.noticeAttachments.push(item)
            }
          })
          this.loading = true;
          this.form.auditType = 4
          submitAudit(this.form).then(() => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.cancelDialog();
          }, () => {
            this.loading = false;
          });
        } else {
          return false;
        }
      });
    },

    // 重置表单
    cancelDialog() {
      this.$emit('cancelDialog', {})
      this.$refs['dataForm'].resetFields()
      this.clearTableData()
      this.visible = false // 关闭时更改页面显示状态
    },

    // -- 穿梭框
    showTransferDialog(transferDialogArr, transferDialogType, transferDialogMultiple, transferDialogQuery) {
      this.transferDialogArr = transferDialogArr; // 表单字段
      this.transferDialogType = transferDialogType; // 判断类型user:人员，unit:职位，department:部门,company:单位,plan:计划等
      this.transferDialogMultiple = transferDialogMultiple; // 是否多选
      if (transferDialogType === 'developer') {
        this.transferCurrent.types = transferDialogQuery;
      }
      // if (transferDialogType === 'contacts') {
      //   this.transferCurrent.jobCategory = transferDialogQuery; // jobCategory:3010 中层领导
      // }
      //重组数组name和id
      this.transferCurrent.currentval = []
      if(this.form[transferDialogArr[0]]) {
        if (this.form[transferDialogArr[0]].indexOf(',') > -1) {
          this.form[transferDialogArr[0]].split(',').forEach((item, i) => {
            this.transferCurrent.currentval.push({name: this.form[transferDialogArr[1]].split(',')[i], id: item})
          })
        } else {
          this.transferCurrent.currentval = [{name: this.form[transferDialogArr[1]], id: this.form[transferDialogArr[0]]}]
        }
      }
      this.transferDialog = true;
    },
    closeTransfer() {
      this.transferDialog = false
      this.transferDialogType = ''
    },
    // 已选定数据的更新判断
    transferDataHandle(e) {
      this.transferDialog = false
      let currentval = [], currentLabel = []
      if (e.list.length > 0) {
        if (e.list.length > 1) {
          e.list.forEach(item => {
            currentval.push(item.id)
            currentLabel.push(item.name)
          })
        } else {
          currentval = [e.list[0].id]
          currentLabel = [e.list[0].name]
        }
        this.$set(this.form, this.transferDialogArr[0], currentval.join(','))
        this.$set(this.form, this.transferDialogArr[1], currentLabel.join(','))
      } else { // 如果返回的数据为空，也将当前页面数值清空
        this.$set(this.form, this.transferDialogArr[0], '')
        this.$set(this.form, this.transferDialogArr[1], '')
      }
      this.transferDialogType = ''
    },
    wordFileHandle(e) {
      this.$set(this.form, "wordFile", e.wordFile);
      this.$set(this.form, "noticeId", e.id);
    },
  }
}
</script>

<style>
.input-with-margin {
  margin-left: 4.5%;
}
.view-with-margin {
  margin-left: 4.5%;
}
</style>
